package com.nti56.springboot.service;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nti56.springboot.exception.MyRuntimeException;
import com.nti56.springboot.mapper.tmsmapper.ProdMstrMapper;
import com.nti56.springboot.model.ProdMstr;
import com.nti56.springboot.model.User;
import com.nti56.springboot.utils.ParamUtil;
import com.nti56.springboot.utils.ParamUtil.Param;

@Service
public class ProdMstrService {
	
	private static final Logger logger = LoggerFactory.getLogger(ProdMstrService.class);

	
	@Autowired
	private ProdMstrMapper prodMstrMapper;
	
	public ProdMstr getById(String pmId) {
		return this.prodMstrMapper.getById(pmId);
	}
	
	public void insert(ProdMstr prodMstr) {
		Param param = ParamUtil.setParam("machNum", prodMstr.getMachNum())
				   				.setParam("shift", prodMstr.getShift())
				   				.setParam("proDate", prodMstr.getProDate());
		Long cnt = prodMstrMapper.countByMap(param);
		if(cnt > 0) {
			logger.error("同一生产日期，同一班次，同一机台，不允许有多个目标产量！");
			throw new MyRuntimeException("同一生产日期，同一班次，同一机台，不允许有多个目标产量！");
		}
		this.prodMstrMapper.insert(prodMstr);
	}
	
	public void update(ProdMstr prodMstr) {
		Param param = ParamUtil.setParam("machNum", prodMstr.getMachNum())
   				.setParam("shift", prodMstr.getShift())
   				.setParam("proDate", prodMstr.getProDate())
				.setParam("pmId", prodMstr.getPmId());
		Long cnt = prodMstrMapper.countByMap(param);
		if(cnt > 0) {
			logger.error("同一生产日期，同一班次，同一机台，不允许有多个目标产量！");
			throw new MyRuntimeException("同一生产日期，同一班次，同一机台，不允许有多个目标产量！");
		}
		this.prodMstrMapper.update(prodMstr);
	}
	
	public List<ProdMstr> findAll(Map params) {
		return prodMstrMapper.findAll(params);
	}
	
	@Transactional(rollbackFor = Exception.class, transactionManager = "tmsTransactionManager")
	public void delete(String pmId){
		prodMstrMapper.delete(pmId);
	}
	
	
}
